package com.lrl.controller;

import com.alibaba.fastjson.JSON;
import com.lrl.pojo.Admin;
import com.lrl.service.AdminService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    AdminService adminService;

    @RequestMapping("/getAllAdmins")
    @ResponseBody
    public String queryAllAdmins() {
        return JSON.toJSONString(adminService.getAdminsList());
    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/updateLoginTime")
    public String updateLoginTime() {
        //从SpringSecurity中获取登录账号
        String adminName = "";
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Object authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        System.out.println(authorities);

        //转型
        if (principal instanceof UserDetails) {
            adminName = ((UserDetails) principal).getUsername();
        } else if (principal instanceof Principal) {
            adminName = ((Principal) principal).getName();
        } else {
            adminName = String.valueOf(principal);
        }

        //修改登录时间
        if (adminService.updateLoginTimeByName(adminName)) {
            return "redirect:/admin/main.html";
        } else {
            return "error";
        }
    }

    @RequestMapping("/toAdminAllPage")
    public String toAdminPage(Model model) {
        List<Admin> adminList = adminService.getAdminsList();
        model.addAttribute("adminList", adminList);
        for (Admin admin : adminList) {
            System.out.println(admin);
        }
        return "admin_test";
    }

    @RequestMapping("/toAdminPage/{account}")
    public String toGuestPage(@PathVariable("account") String name, Model model) {
        System.out.println(name);
        Admin admin = adminService.getAdminByName(name);
        model.addAttribute("admin", admin);
        System.out.println(admin);
        return "guest_test";
    }
}
